import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter, RouterContext } from 'react-router-dom';
import { match } from 'react-router';
import { applyMiddleware, createStore } from 'redux';
import { Provider } from 'react-redux';
import { AppContainer } from 'react-hot-loader';
import thunkMiddleware from 'redux-thunk';
import App from '../../app/App';
import routes from '../routes.js';
import reducer from '../../app/reducer/index';

function responseWithCheck (ctx, store, resolve, reject) {
    setImmediate(() => {
        let state = store.getState();
        if (state.requestStatus.status === 'isFetching') {
            return setImmediate(responseWithCheck, ctx, store, resolve, reject);
        }
        return resolve('done');
    });
}

async function routerHandle (ctx, next) {
    let context = {};

    // 第一次渲染
    let store = createStore(reducer, {
        loginData: ctx.session.loginData || {},
        orderList: {},
        goodList: {},
        shelfList: {},
        buildList: {},
        requestStatus: {},
    },
    applyMiddleware(
        thunkMiddleware
    ));
    // if (ctx.url.indexOf('.css') === -1 && ctx.url.indexOf('.js') === -1 && ctx.url.indexOf('.json') === -1 && ctx.url.indexOf('webpack') === -1) {
    //     console.log('我是初始的state');
    //     console.log(ctx.session);
    //     console.log('我是初始的state');
    //     console.log(store.getState());
    //     console.log('我是初始的state');
    // }
    let markup = ReactDOMServer.renderToString(
        <AppContainer>
            <Provider store={store}>
                <StaticRouter
                    location={ctx.url}
                    context={context}>
                    <App />
                </StaticRouter>
            </Provider>
        </AppContainer>
    );
    await (new Promise((resolve, reject) => {
        responseWithCheck(ctx, store, resolve, reject);
    })).then(res => {
        // do something
    });

    // 第二次渲染，把第一次渲染ajax请求数据后的状态做为第二次渲染的初始状态
    store = createStore(reducer, store.getState(),
        applyMiddleware(
            thunkMiddleware
        )
    );
    // if (ctx.url.indexOf('.css') === -1 && ctx.url.indexOf('.js') === -1 && ctx.url.indexOf('.json') === -1 && ctx.url.indexOf('webpack') === -1) {
    //     console.log('我是第二次渲染后的state');
    //     console.log(store.getState());
    // }
    markup = ReactDOMServer.renderToString(
        <AppContainer>
            <Provider store={store}>
                <StaticRouter
                    location={ctx.url}
                    context={context}>
                    <App />
                </StaticRouter>
            </Provider>
        </AppContainer>
    );
    await ctx.render('index.html', {
        root: markup,
        state: JSON.stringify(store.getState()),
        manifest: ctx.session.manifest || {},
        page: global.__defaultQuery ? global.__defaultQuery.page : 0,
    });
    next();
}
export default routerHandle;
